const util = require('../../utils/util.js');
const {
  $Toast
} = require('../..//dist/base/index');

Page({
  data: {
    userInfo: {},
    labels: 'Node',
    value: '',
    article_img: ['/images/plus.png'],
    article_content: [],
    content: {}
  },

  onLoad: function(options) {
    this.getCategories();
  },

  onReady: function() {

  },

  onShow: function() {

  },

  onHide: function() {

  },

  onUnload: function() {

  },

  onPullDownRefresh: function() {

  },

  onReachBottom: function() {

  },

  onShareAppMessage: function() {

  },

  getCategories: function() {
		var that = this;
    var userInfo = wx.getStorageSync("loginInfo");
    
    if (!userInfo) {
      wx.showToast({
        title: '请先登录!',
        icon: 'none',
        duration: 1000,
        mask: true
      });
			wx.reLaunch({
				url: '/pages/userinfo/userinfo',
			});
    } else {
			var alterArticle = wx.getStorageSync("alterArticle");

			console.log(alterArticle);

			if(alterArticle) {
				this.setData({
					userInfo: userInfo,
					['content.author']: userInfo.username,
					['content.openid']: userInfo.openid,
					['content.title']: alterArticle.title,
					['content.id']: alterArticle.id,
					labels: [alterArticle.labels],
					article_img: alterArticle.article_img,
					article_content: alterArticle.article_content
				});
			} else {
				this.setData({
					userInfo: userInfo,
					['content.author']: userInfo.username,
					['content.openid']: userInfo.openid
				});
			}

			wx.request({
				url: util.basePath + '/article/v1/categories',
				method: "post",
				data: {},
				header: {
					'content-type': 'application/json'
				},
				success(res) {
					if (res.data.status == 200) {
						that.setData({
							labels: res.data.payload
						});
					}
				}
			});
    }
  },
  getSelectLabels: function(e) {
    this.setData({
      ['content.labels']: e.detail
    });
  },
  upload_img: function(e) {
    var that = this;

    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;

        wx.uploadFile({
          url: util.basePath + '/users/upload_avatar', 
          filePath: tempFilePaths[0],
          name: 'avatar',
          success(res) {
            var result = JSON.parse(res.data);
            if (result.status == 200) {
              //如果article_img是默认图片，则article_img置空
              var article_img = that.data.article_img;

              //如果上传图片下标在article_img已存在，则直接更新
              article_img[e.currentTarget.dataset.index] ? article_img[e.currentTarget.dataset.index] = result.payload.avatar_path : article_img.push(result.payload.avatar_path);

              that.setData({
                article_img: article_img
              });
            }
          }
        });
      }
    });
  },
  titleInput: function(e) {
    this.setData({
      ['content.title']: e.detail.value
    });
  },
  textInput: function(e) {
    this.setData({
      ['content.content']: e.detail.value
    });
  },
  setContent: function(e) {
    var article_content = this.data.article_content ? this.data.article_content : [];
    article_content[e.currentTarget.dataset.index] != 'undefine' ? article_content[e.currentTarget.dataset.index] = e.detail.value : article_content.push(e.detail.value);
    this.setData({
      article_content: article_content
    });
  },
  add_article: function() {
    if (this.data.article_content.length != this.data.article_img.length) {
      wx.showToast({
        title: '请输入正文!',
        icon: 'none',
        duration: 1000,
        mask: true
      });
    } else {
      var flag = true;
      this.data.article_content.forEach(article => {
        if (!article) {
          flag = false;
        }
      });

      if (flag) {
        var article_img = this.data.article_img;
        article_img.push('/images/plus.png');
        this.setData({
          article_img: article_img
        });
      } else {
        wx.showToast({
          title: '正文不完整!',
          icon: 'none',
          duration: 1000,
          mask: true
        });
      }
    }
  },
  show_article: function() {
    var that = this;
    if (!this.data.content.title || !this.data.content.author || !this.data.content.labels || this.data.article_img[0] == '/images/plus.png' || !this.data.article_content || !this.data.content.openid || this.data.article_content.length != this.data.article_img.length) {
      wx.showToast({
        title: '参数不全!',
        icon: 'none',
        duration: 1000,
        mask: true
      });
    } else {
      var flag = true;

      this.data.article_content.forEach(article => {
        if (!article) {
          flag = false;
        }
      });

      if (flag) {
        var param = {
          title: this.data.content.title,
          author: this.data.content.author,
          labels: this.data.content.labels,
          main_pic: this.data.article_img[0],
          openid: this.data.content.openid,
          gist: this.data.article_content[0]
        };

        //将输入文本手动转化成html，设置div的class支持MD插件美化
        var content = '<div class="markdown-text">';
        var count = 0;
        this.data.article_content.forEach(article => {
          //使用p标签将每一段内容包住
          content = content + '<p>' + article + '</p>'

          //如果本段文本有插入图片，则使用img标签插入图片
          if (that.data.article_img[count] != '/images/plus.png') {
            content = content + '<p><img src="' + that.data.article_img[count] + '"></p>'
          }

          count++;
        });

        content += '</div>'
        param.content = content;

        //将数据存入缓存
        wx.setStorage({
          key: 'showContent',
          data: param,
        });

        //跳转预览界面预览
        wx.navigateTo({
          url: '/pages/showcontent/showcontent',
        });
      } else {
        wx.showToast({
          title: '正文不完整!',
          icon: 'none',
          duration: 1000,
          mask: true
        });
      }
    }
  },
  submit_article: function() {
		console.log({
			id: this.data.content.id,
			title: this.data.content.title,
			author: this.data.content.author,
			labels: this.data.content.labels,
			main_pic: this.data.article_img[0],
			openid: this.data.content.openid,
			gist: this.data.article_content[0],
			avatar: this.data.userInfo.avatar
		})
    var that = this;
    if (!this.data.content.title || !this.data.content.author || !this.data.content.labels || this.data.article_img[0] == '/images/plus.png' || !this.data.article_content || !this.data.content.openid || this.data.article_content.length != this.data.article_img.length) {
      wx.showToast({
        title: '参数不全!',
        icon: 'none',
        duration: 1000,
        mask: true
      });
    } else {
      var flag = true;

      this.data.article_content.forEach(article => {
        if (!article) {
          flag = false;
        }
      });

      if (flag) {
        var param = {
					id: this.data.content.id,
          title: this.data.content.title,
          author: this.data.content.author,
          labels: this.data.content.labels,
          main_pic: this.data.article_img[0],
          openid: this.data.content.openid,
          gist: this.data.article_content[0],
					avatar: this.data.userInfo.avatar
        };

        //将输入文本手动转化成html，设置div的class支持MD插件美化
        var content = '<div class="markdown-text">';
        var count = 0;
        this.data.article_content.forEach(article => {
          //使用p标签将每一段内容包住
          content = content + '<p>' + article + '</p>'

          //如果本段文本有插入图片，则使用img标签插入图片
          if (that.data.article_img[count] != '/images/plus.png') {
            content = content + '<p><img src="' + that.data.article_img[count] + '"></p>'
          }

          count++;
        });

        content += '</div>'
        param.content = content;

				//如果文章id存在，则修改文章，否则更新文章
				if(this.data.content.id) { 
					wx.request({
						url: util.basePath + '/article/v1/updateArticle',
						method: "post",
						data: param,
						header: {
							'content-type': 'application/json'
						},
						success(res) {
							if (res.data.status == 200) {
								wx.removeStorage({
									key: 'alterArticle',
									success: function(res) {
										wx.showToast({
											title: '更新文章成功!',
											icon: 'success',
											duration: 1000,
											mask: true
										});

										wx.reLaunch({
											url: '/pages/index/index'
										});
									},
								});
							} else {
								wx.showToast({
									title: '接口出现异常!',
									icon: 'none',
									duration: 1000,
									mask: true
								});
							}
						}
					});
				} else {
					//进行发表文章
					wx.request({
						url: util.basePath + '/article/v1/saveContent',
						method: "post",
						data: param,
						header: {
							'content-type': 'application/json'
						},
						success(res) {
							if (res.data.status == 200) {
								wx.showToast({
									title: '发表文章成功!',
									icon: 'success',
									duration: 1000,
									mask: true
								});

								wx.reLaunch({
									url: '/pages/index/index',
								})
							} else {
								wx.showToast({
									title: '接口出现异常!',
									icon: 'none',
									duration: 1000,
									mask: true
								});
							}
						}
					});
				}
      } else {
        wx.showToast({
          title: '正文不完整!',
          icon: 'none',
          duration: 1000,
          mask: true
        });
      }
    }
  }
});